<template>
  <div class="peopleDo">
    <!-- 头部按钮 -->
    <div class="headerDiv">
      <div class="headerDiv_left">
          <i :class="rotate ? 'el-icon-refresh rotateGo' : 'el-icon-refresh rotateBack'" @click="refreshBtn"></i>
          <el-button type="primary" @click="addPeople">添加 </el-button>
          <el-button type="primary" @click="deletMessage(multipleSelection)">批量删除</el-button>
      </div>
      <el-form :inline="true" :model="formInline" class="demo-form-inline headerDiv_right">
          <el-form-item>
            <el-input v-model="formInline.user" placeholder="请输入要搜索的姓名" clearable></el-input>
          </el-form-item>
          <el-form-item>
            <el-button  type="primary" @click="queryMessage">查询</el-button>
          </el-form-item>
      </el-form>      
    </div>

    <!-- 表格 -->
    <div class="contentDiv">
      <el-table
        ref="multipleTable"
        :data="dataShow"
        tooltip-effect="dark"
        :header-cell-style="{background:'#eef1f6',color:'#606266'}"
        style="width: 100%"
        :row-key="getRowKeys"
        @selection-change="handleSelectionChange">
        <el-table-column
          :reserve-selection="true"
          type="selection"
          align="center"
          width="55">
        </el-table-column>
        <el-table-column
          prop="college"
          label="学院"
          align="center"
          >
        </el-table-column>
        <el-table-column
          prop="loginCode"
          label="学号"
          align="center"
          >
        </el-table-column>
        <el-table-column
          prop="empClass"
          label="班别"
          align="center"
          >
        </el-table-column>
        <el-table-column
          prop="empName"
          label="姓名"
          align="center"
         >
        </el-table-column>
        <el-table-column
          prop="roleName"
          label="角色名"
          align="center"
          show-overflow-tooltip>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="120">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" @click="editMessage(scope.row)" circle></el-button>
            <el-button type="danger" icon="el-icon-delete" @click="deletMessage(scope.row.empId)" circle></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页按钮 -->
    <div class="pagingTool">
       <el-pagination background @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                  :current-page="current" 
                  :page-size="pageSize"
                  layout="prev, pager, next, jumper , slot, total" 
                  :total="total" class="pageInfo">
          <span id="sure">确定</span>
       </el-pagination>
    </div>

    <!-- 模态框 -->
    <el-dialog class="addDialog" :title="dialogTitle" :visible.sync="dialogFormVisible" width="65%">
      <el-form class="addDialog_form" :model="form" :rules="rulesCheck" label-position="right" label-width="110px">
        <div class="addDialog_left">
            <el-form-item label="学号或教工号" prop="loginCode">
              <el-input type="loginCode" class="addDialog_input" v-model.number="form.loginCode" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="姓名" prop="empName">
              <el-input class="addDialog_input" v-model="form.empName" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="性别" prop="empSex">
              <el-radio-group v-model="form.empSex">
                <el-radio label="男"></el-radio>
                <el-radio label="女"></el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="出身年月" prop="birthday">
                  <el-col>
                    <el-date-picker type="date" placeholder="请选择日期" v-model="form.birthday" class="addDialog_input"></el-date-picker>
                  </el-col>
                </el-form-item>
            <el-form-item label="学院" prop="college">
              <el-input class="addDialog_input" v-model="form.college" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="班级" prop="empClass">
                <el-input class="addDialog_input" v-model="form.empClass" autocomplete="off"></el-input>
              </el-form-item>
        </div>
        
        <div class="addDialog_right">
              <el-form-item label="设置密码" prop="password">
                <el-input class="addDialog_input" v-model="form.password" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="选择角色" prop="roleId">
                <el-select v-model="form.roleId" placeholder="请选择角色" class="addDialog_input">
                  <el-option :label="item.roleName" :value="item.roleId" v-for="item in selectRole" :key="item.roleId" selected="from.roleId == item.roleId"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="身份证号" prop="idNum">
                <el-input class="addDialog_input" v-model="form.idNum" autocomplete="off" maxlength="18" ></el-input>
              </el-form-item>
              <el-form-item label="电话号码" prop="telephone">
                <el-input class="addDialog_input" v-model.number="form.telephone" autocomplete="off" maxlength="11" ></el-input>
              </el-form-item>
              <el-form-item label="家庭地址" prop="address">
                  <el-input type="textarea" v-model="form.address"></el-input>
              </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveMessage">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { axiosRequest } from "@/utils/axiosRequest";
import { Base64 } from 'js-base64';
export default {
  data() {
    return {
      rotate: false,
      //搜索框
      formInline: {  user: '',},
      queryDatas: [], //搜索的数据
      tableData: [],  //请求得到的表格所有数据
      multipleSelection: [],  //多选
      // 模态框
      dialogFormVisible: false,
      dialogTitle: '添加人员',
      form: {
        loginCode: '',
        empName: '',
        empSex: '',
        birthday: '',
        college: '',
        empClass: '',
        roleId: '',
        roleName: '',
        idNum: '',
        telephone: '',
        address: '',
        password: ''
      },
      oldPassword: '',
      selectRole:[],   //选择的角色
      // 分页
      current:1,      //默认显示第一页数据
      pageSize:5,     //每页显示多少条数据
      total:0,        //一共多少条后台数据
      dataShow: [],   //当前显示的数据
      pageNum: 1,     //共有几页
      totalPage: [],  //所有页面的数据

      // 表单校验
      rulesCheck:{
        loginCode: [
            { required: true, message: '学号或教工号不能为空'},
            { type: 'number', message: '学号或教工号必须为数字值'}
        ],
        empName: [
          { required: true, message: '请输入用户名字', trigger: 'blur' },
        ],
        empSex: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        birthday: [
          { type: 'date', required: true, message: '请选择出生日期', trigger: 'change' }
        ],
        college: [
          { required: true, message: '请输入所在学院名称', trigger: 'blur' },
        ],
        empClass: [
          { required: true, message: '请输入所在的班级', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '密码长度在 6~20 个字符', trigger: 'blur' }
        ],
        roleId: [
          { required: true, message: '请至少选择一个角色', trigger: 'change' }
        ],
        idNum: [
          { required: true, message: '身份证号不能为空'},
          { min: 18, max: 18, message: '身份证号长度为18位', trigger: 'blur' }
        ],
        telephone: [
          { required: true, message: '号码必须为数字值'},
          { min: 3, max: 11, message: '号码长度为 3~11 位', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请填写家庭住址', trigger: 'blur' }
        ]
      },
    }
  },
  methods: {
    // 刷新按钮事件
    refreshBtn() {
      var self = this;
      if(self.rotate == false){
        self.rotate = true;
      }else {
        self.rotate = false;
      }
      self.askDatas();
      self.$message({
          showClose: true,
          message: '刷新成功！！！',
          type: 'success'
        });
    },

    // 添加按钮事件
    addPeople() {
      var self = this;
      self.dialogFormVisible = true;
      self.form = {};
    },   

    // 查询按钮事件
    queryMessage() {
      var self = this;
      var newTables = self.queryDatas;
      var newsQuerys = self.formInline.user.toLowerCase();
      let newArrays = [];
      newArrays = newTables.filter( function(e){
         if(JSON.stringify(e).toLowerCase().indexOf(newsQuerys) !== -1 ){
           return e;
         }
      });
      if(newArrays.length !== 0){
          self.$message({
              message: '查找成功，这是一条成功消息',
              type: 'success'
          });
      } else {
         self.$message({
              message: '我记得没有这一条信息的哦',
              type: 'warning'
          });
      }
      self.total = newArrays.length;
      self.pageNum = Math.ceil(self.total / self.pageSize) || 1;
      for(let i = 0; i < self.pageNum; i++){
        self.totalPage[i] = newArrays.slice(self.pageSize * i, self.pageSize * (i + 1))
      }
      self.dataShow = self.totalPage[self.current - 1];
    },

    // 表格选择框
    handleSelectionChange(val) {
        this.multipleSelection = val;
    },

    //表格多选切换页面回显
    getRowKeys(row) {
      return row.empId;
    },

    // 编辑按钮事件
    editMessage(row) {
      var self = this;
      if(row.roleName == "管理员") {
        self.$message({
            type: 'warning',
            message: '管理员不可编辑!'
          });
        return;
      }
        self.dialogTitle = "编辑人员";
        self.form = row;
        self.oldPassword = row.password;
        self.dialogFormVisible=true;
    },

    // 批量删除按钮事件， 删除按钮事件
    deletMessage(id) {
      let self = this;
      let selectList = [];
      let newSelects = self.multipleSelection;
      if(id.constructor !== Array){
        selectList.push(id);
      } else {
        newSelects.forEach(e => { selectList.push(e.empId) });
      }
      let deleteDatas = {
        idList: selectList,
      }
      //删除提示框
      if(selectList!=''){
        if(selectList==1){
            self.$message({
                type: 'warning',
                message:'管理员不可删除！',
              })
              return;
        }
        self.$confirm('此操作将永久删除当前记录, 是否继续?', '提示',  {
            confirmButtonText:  '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
        axiosRequest("delete", "/emp/del",deleteDatas).then((result) => {
            if (result.data.code === 200) {
                  self.$message({
                  type: 'success',
                  message: '删除成功!'
                  });
                  self.askDatas();
                  } else {
                  self.$message.error(result.data.data);
                  }
          })
          }).catch(() =>  {
            self.$message({
                type: 'info',
                message:  '已取消删除',
            })
          })
      }else{
          self.$message({
              type: 'warning',
              message:  '请选择要删除的记录!',
          });
      }
    },

    // 模态框-确定按钮事件
    saveMessage() {
      var self = this;
      let newId = self.form.roleId;
      let newRole = self.selectRole.filter((n)=> n.roleId == newId);
      if(newRole.length !== 0){
          self.form.roleName = newRole[0].roleName;
      }else{
        return;
      }
      self.form.password = Base64.encode(self.form.password);
      let params = self.form;
      axiosRequest("post", "/emp/save", params).then((result) => {
        if (result.data.code === 200) {
          if(params.empId==JSON.parse(window.sessionStorage.getItem("userInfo")).user.loginId){
            self.form.password = Base64.decode(self.form.password);
            if(self.oldPassword!=self.form.password){
              self.$confirm('此操作涉及您当前登录账号里的密码修改，需重新登录！！！', '提示', {
              cancelButtonText: '取消',
              confirmButtonText: '确定',
              type: 'warning',
            }).then(() => {
              self.$router.push({ name: "Login" });
            }).catch(() => {
              self.form.password = Base64.decode(self.form.password);
            })
            }
          }else{
            self.$message({
              type: 'success',
              message: self.dialogTitle + '成功!',
            });
            self.form.password = Base64.decode(self.form.password);
            self.askDatas();
            self.dialogFormVisible = false;
          }
        }
        else {
          self.askDatas();
          self.form.password = Base64.decode(self.form.password);
          self.$message.error(result.data.data);
        }
      });
    },

    //每页显示
    handleSizeChange(val) {
      this.pageSize = val;
      this.current=1;
    },

    //显示页
    handleCurrentChange(val) {
      this.current = val;
      this.askDatas();
    },

    // 请求table信息, 查询按钮事件, 数据分页
    askDatas() {
      var self = this;
      axiosRequest("get", "/emp/listAll", null).then((res) => {
        if (res.data.code === 200) {
            self.total = res.data.data.length;
            self.tableData = res.data.data.reverse();
            self.queryDatas = res.data.data;
            self.pageNum = Math.ceil(self.total / self.pageSize) || 1;
              for(let i = 0; i < self.pageNum; i++){
                self.totalPage[i] = self.tableData.slice(self.pageSize * i, self.pageSize * (i + 1))
              }
            self.dataShow = self.totalPage[self.current - 1];
          } else {
            self.$message({
              showClose: true,
              message: '错了哦，请求信息失败了！！！',
              type: 'error',
            });
          }
      });
    },

  },
  
  mounted: function() {
    var self = this;
    // 请求table信息
    self.askDatas();

    // 请求角色信息
    axiosRequest("get","/roles/list",null).then((res) => {
          if (res.data.code === 200) {
              self.selectRole = res.data.data;
            } else {
              self.$message({
                showClose: true,
                message: '错了哦，请求信息失败了！！！',
                type: 'error'
              });
            }
        });
  }
}
</script>

<style lang="less" scoped>
.peopleDo {
  padding-left: 10px;
  position: relative;
}

.headerDiv {
  width: 100%;
  display: flex;
  justify-content: space-between;
}

.headerDiv_left {
  width: 35%;
  min-width: 320px;
}

.headerDiv_left /deep/ .el-button {
  margin-top: 4px;
  margin-left: 10%;
  padding: 8px 11px;
}

.headerDiv_left > i {
  margin-left: 5%;
}

.rotateBack {
  transform: rotate(180deg);
  transition: all 2s;
}

.rotateGo {
  transform: rotate(-180deg);
  transition: all 2s;
}

.headerDiv_left > i:hover {
  color: #218ef3;
  cursor:  pointer;
}

.headerDiv_right /deep/ .el-button {
  padding: 8px 15px;
}

.headerDiv_right /deep/ .el-input__inner {
    height: 35px;
}

.tableDetails {
  text-align: center;
}

.pagingTool{
  position: absolute;
  top: 458px;
}

#sure {
    border: 1px solid #DCDFE6;
    text-align: center;
    line-height: 25px;
    display: inline-block;
    margin: 0px 15px;
    cursor: pointer;
    width: 4%;
    border-radius: 3px;
}

.addDialog /deep/ .el-dialog__body {
    padding: 10px 20px 0px 20px;
    color: #606266;
    font-size: 14px;
    word-break: break-all;
}

.addDialog_left,.addDialog_right {
    width: 50%;
}

.addDialog /deep/ .el-textarea__inner {
    padding: 5px 55px;
}

.addDialog_form {
    display: flex;
    justify-content: space-between;
}

.addDialog_input {
    width: 90%;
}

.el-radio-group {
    font-size: 0;
    margin-top: 0px;
}

.addDialog /deep/ .el-textarea__inner {
    width: 90%;
    height: 110px;
    padding: 0px 5px;
}

</style>
